package www.lagou.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {
    public static DataSource dataSource;

    static {
        Properties properties = null;
        try {
            properties = new Properties();
            InputStream i = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(i);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    public static DataSource getDataSource(){
        return dataSource;
    }

    public static void close(Connection con, Statement statement) {
        if (null != con && null != statement) {
            try {
                statement.close();
                con.close();

            } catch (SQLException e) {
                e.printStackTrace();

            }
        }
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet) {
        if (null != con && null != statement && null != resultSet) {
            try {
                statement.close();
                con.close();
                resultSet.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}